import React, {useState, useEffect} from 'react';
import { Modal, Form, Input, Radio, Upload, Button, message, Spin } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { FormInstance } from 'antd/lib/form';
import { VersionListItem } from '../data.d';

interface UpdateModelProps {
  modalVisible: boolean;
  onSubmit: (callback:string) => void;
  onCancel: () => void;
}

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const formRef = React.createRef<FormInstance>();

const UpdateModel: React.FC<UpdateModelProps> = (props) => {

  const { modalVisible, onSubmit, onCancel } = props;
  const [fileList, setFileList] = useState<VersionListItem[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [uploadDisabled, setUploadDisabled] = useState<boolean>(true);
  const [form] = Form.useForm();
  

  useEffect(() => {
    if(modalVisible){
      setFileList([]);
      setUploadDisabled(true);
      form.resetFields();
    }
  },[modalVisible]);

  const handleUpdate = () => {
    if (!form) return;
    form.submit();
  };

  const modalFooter = { okText: '保存', onOk: handleUpdate, onCancel };

  const handleFinish = (values: { [key: string]: any }) => {
    setLoading(true);
    let formData = new FormData();
    formData.append('file', fileList[0]);
    for(let item in values) {
      if(item !== 'file' && values[item]) {
        formData.append(item, values[item]);
      }
    }

    const request = new Request('/api/system/apk_version/add', {
      method: 'POST',
      body: formData,
      headers: {
        'Authorization':localStorage.getItem('token'),
      },
    });
    fetch(request).then(res =>res.json()).then((res => {
      setLoading(false);
      if (res.code === 200) {
          message.success("添加成功");
          props.onSubmit('success');
      } else {
          message.error("添加失败，"+res.message);
      }
    }));
  };

  const uploadProps = {
    accept:'.apk',
    onRemove: (file:any) => {
        const index = fileList.indexOf(file);
        const newFileList = fileList.slice();
        newFileList.splice(index, 1);
        setFileList(newFileList);
        if(newFileList.length == 0){
          setUploadDisabled(true);
        }
    },
    beforeUpload: (file:any) => {
        if(fileList.length == 0){
          setFileList([...fileList, file]);
          setUploadDisabled(false);
        }
        
      return false;
    },
    fileList,
  };

  const renderContent = () => {
    return (
      <Spin spinning={loading}>
        <Form {...layout} ref={formRef} form={form} onFinish={handleFinish}>
          <Form.Item name="versionNo" label="版本号" rules={[{ required: true, max: 64, whitespace: true, pattern:/^(\d{8})?$/, message:'请输入版本号,格式为8位正整数,如202012+两位小版本号' }]}>
          <Input placeholder="请输入版本号" style={{width:200}}/>
          </Form.Item>
          <Form.Item name="versionName" label="版本名" rules={[{ required: true, max: 256, whitespace: true }]}>
          <Input placeholder="请输入版本名" style={{width:200}}/>
          </Form.Item>
          <Form.Item name="file" label="安装包" rules={[{ required: true}]}>
            <Upload {...uploadProps}>
              <Button type="primary" icon={<UploadOutlined />} disabled={!uploadDisabled}>选择文件</Button>
            </Upload>
          </Form.Item>
          <Form.Item name="type" label="包类型" rules={[{ required: true}]} initialValue="APK">
            <Radio.Group defaultValue="APK">
              <Radio value="APK">APK包</Radio>
          </Radio.Group>
          </Form.Item>
          <Form.Item name="description" label="版本描述">
            <Input.TextArea
              rows={4}
              style={{resize:"none"}} 
              maxLength={256}
            />
          </Form.Item>
        </Form>
      </Spin>
    );
  };

  return (
    <Modal
      confirmLoading={loading}
      destroyOnClose
      title="新建版本"
      width={400}
      visible={modalVisible}
      onCancel={() => onCancel()}
      {...modalFooter}
    >
      {renderContent()}
    </Modal>
  );
};

export default UpdateModel;
